#!/usr/bin/perl

$HOME_DIR = "/home/one-tenth";
$HOME_DIR = $ENV{'CHOPSET_HOME'} if($ENV{'CHOPSET_HOME'} ne '');

require "$HOME_DIR/config.ph";

#$OUTPUT_JSON_FILE_PATH = "/var/www/cgi-bin/limura/Master/";
$OUTPUT_JSON_FILE_PATH = "/var/www/html/limura/";

use Socket;
use JSON;

$SIG{'ALRM'} = sigAlarmHandler;

$UDPRecvPort = shift;
$USER_NAME = shift;

$OUTPUT_JSON_FILE_PATH .= "${USER_NAME}.txt";

$jsonObj = {};

socket(SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('udp'));
bind(SOCKET, pack_sockaddr_in($UDPRecvPort, INADDR_ANY));

&daemon();
alarm 2;

$prevTime = time();
while(1){
	recv(SOCKET, $buf, 50000, 0);
	$nowTime = time();
	if(length($buf) > 0 && $buf =~ m/{/){
		$buf = "{$buf}";
		my($localJsonObj);
		#eval("\$localJsonObj = from_json(\$buf)");
		$localJsonObj = eval("from_json(\$buf);");
		if(defined($localJsonObj)){
			my($nodeName);
			foreach $nodeName (keys(%$localJsonObj)){
				$jsonObj->{$nodeName} = $localJsonObj->{$nodeName};
				$jsonObj->{$nodeName}->{"LastUpdateTime"} = $nowTime;
			}
		}
	}
}

sub sigAlarmHandler{
	my($nowTime) = time();
	if(open(FILE, ">$OUTPUT_JSON_FILE_PATH")){
		my($nodeName);
		foreach $nodeName (keys(%$jsonObj)){
			$jsonObj->{$nodeName}->{"UpdateDiffTime"} = $nowTime - $jsonObj->{$nodeName}->{"LastUpdateTime"};
		}
		flock(FILE, 2);
		seek(FILE, 0, 0);
		truncate(FILE, 0);
		print FILE to_json($jsonObj);
		flock(FILE, 8);
		close(FILE);
	}
	alarm 2; # see you next time...
}
